package vn.ikame.android.truyenf17;

import java.io.IOException;

import vn.ikame.android.adapter.ListCategoryAdapter;
import vn.ikame.android.handler.CHandler;
import vn.ikame.android.handler.Constant;
import vn.ikame.android.plugin.BaseActivity;
import vn.ikame.android.plugin.ChatActivity;
import vn.ikame.android.plugin.CustomDialog;
import vn.ikame.android.truyenf17voz.R;
import vn.ikame.android.utils.CStore;
import vn.ikame.android.utils.CommonUtils;
import vn.ikame.android.utils.XMLParser;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
import com.loopj.android.image.SmartImageView;

public class CategoryList extends BaseActivity{
	public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
	public ListView gridview;
	public ListCategoryAdapter mGridViewAdapter;
	private AlertDialog.Builder alert;
	private ProgressDialog mProgressDialog;
	private AdView adView;
	
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.categorylist);
		CHandler.store = new CStore(this);
		
		if (StoryList.trackGA) {
			StoryList.generalTracker = GoogleAnalyticsTracker.getInstance();
			StoryList.generalTracker.startNewSession("UA-33515341-2",
					getApplicationContext());
			StoryList.generalTracker.trackTransactions();
			StoryList.generalTracker.trackPageView("FromF17WithLove");
			StoryList.generalTracker.dispatch();
			StoryList.trackGA = false;

			StoryList.detailsTracker = GoogleAnalyticsTracker.getInstance();
			StoryList.detailsTracker.startNewSession("UA-33515341-6",
					getApplicationContext());
			StoryList.detailsTracker.trackTransactions();
			StoryList.detailsTracker.trackPageView("FromF17WithLove_LaunchApp");
			StoryList.detailsTracker.dispatch();
		}

		
		LinearLayout lLinLayout = (LinearLayout) findViewById(R.id.layoutcatelist);

		RelativeLayout.LayoutParams adParams2 = new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.WRAP_CONTENT,
				RelativeLayout.LayoutParams.WRAP_CONTENT);
		adParams2.addRule(RelativeLayout.ALIGN_BOTTOM);
		adParams2.addRule(RelativeLayout.CENTER_IN_PARENT);

		adView = new AdView(this, AdSize.SMART_BANNER, "a1502465d6a93ed");
		adView.loadAd(new AdRequest());
		lLinLayout.addView(adView, adParams2);
		 
		gridview = (ListView) findViewById(R.id.gridview);
		
		if (CommonUtils.isNetworkConnected(this)) {
			if (CHandler.categoryList.isEmpty()) {
				initCategory();
			} else {
				mGridViewAdapter = new ListCategoryAdapter(CategoryList.this, R.layout.maingridview, CHandler.categoryList);
				gridview.setAdapter(mGridViewAdapter);
				
				gridview.setOnItemClickListener(new OnItemClickListener() {
	
					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						// TODO Auto-generated method stub
						
						CHandler.cateID = CHandler.categoryList.get(position).getId();
						startActivity(new Intent(CategoryList.this, StoryList.class));
						CategoryList.this.finish();
					}
	
				});

			}
		} else {
			alert = new AlertDialog.Builder(this);
			alert.setMessage("Vui lòng kiểm tra lại kết nối mạng");
			alert.setPositiveButton("Thử lại",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							initCategory();
						}
					});
			alert.setNegativeButton("Thoát",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							CategoryList.this.finish();
							System.gc();
							android.os.Process.killProcess(android.os.Process.myPid());
						}
					});

			alert.setCancelable(true);
			alert.show(); 

			
		}
	}
	
	public void createNotificationAlert(){
		if(noti.isShow()){
			return;
		}
		
		try {
			System.out.println("Show Notify");
			noti.setShow(true);
			noti.setAlert(new CustomDialog.Builder(this));
			noti.getAlert().setMessage(noti.getContent());
			
			SmartImageView image = (SmartImageView)noti.getAlert().getView().findViewById(R.id.icon);
			image.setImageUrl(noti.getIconLink());
			
			TextView text = (TextView)noti.getAlert().getView().findViewById(R.id.name);
			text.setText(noti.getName());
			
			if(!noti.getAppLink().equals("")){
				noti.getAlert().setPositiveButton("Xem app", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();
						Intent intent = new Intent(Intent.ACTION_VIEW);
						intent.setData(Uri.parse(noti.getAppLink()));
						startActivity(intent);
					}
				});
			}

			noti.getAlert().setNegativeButton("Thoát", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					dialog.dismiss();
					finish();
					System.gc();
					android.os.Process.killProcess(android.os.Process.myPid());
				}
			});
			noti.getAlert().setCancelable(true);
			noti.getAlert().show();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.menu_category, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.chat:
//			CategoryList.this.finish();
			startActivity(new Intent(CategoryList.this, ChatActivity.class));
			break;
		case R.id.moregame:
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setData(Uri.parse("market://search?q=ikame"));
			startActivity(intent);
			break;
		case R.id.rateapp:
			Intent intent1 = new Intent(Intent.ACTION_VIEW);
			intent1.setData(Uri.parse("market://details?id=vn.ikame.android.truyenf17voz"));
			startActivity(intent1);
			break;
		case R.id.gotomark:
			if (CHandler.store.getStoryID() > 0) {
				CHandler.storyName = CHandler.store.getStoryName();
				CHandler.chapID = CHandler.store.getChapID();
				CHandler.storyID = CHandler.store.getStoryID();
				CHandler.chapPos = CHandler.store.getChapPos();
				CHandler.cateID = CHandler.store.getCateID();
				initChapList();
				CHandler.isReadMarkChap = true;

			} else {
				Toast.makeText(this, "Chưa có chap nào được đánh dấu",
						Toast.LENGTH_SHORT).show();
			}
			break;
		case R.id.share:
			
			Intent sharingIntent = new Intent(Intent.ACTION_SEND);
			sharingIntent.setType("text/plain");
			sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "https://play.google.com/store/apps/details?id=vn.ikame.android.truyenf17voz");
			sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Ứng dụng Truyện Ngắn F17 Voz");
			startActivity(Intent.createChooser(sharingIntent, "Share using"));
			
			/*
			if (CommonUtils.isNetworkConnected(this)) {
				initCategory();
			} else {
				alert = new AlertDialog.Builder(this);
				alert.setMessage("Vui lòng kiểm tra lại kết nối mạng");
				alert.setPositiveButton("Thử lại",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								initCategory();
							}
						});
				alert.setNegativeButton("Thoát",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								CategoryList.this.finish();
								System.gc();
								android.os.Process
										.killProcess(android.os.Process.myPid());
							}
						});

				alert.setCancelable(true);
				alert.show();
			}
			*/
			break;
		case R.id.about:
			createAboutMessage();
			break;

		}
		return true;
	}

	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if(!CHandler.store.isRate()){
				createExitMessage();
			} else {
				createExit2Message();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	public void createExitMessage() {
		alert = new AlertDialog.Builder(this);
		alert.setTitle("Thoát ứng dụng");
		alert.setMessage("Bạn có muốn rate app này trên play store?");
		alert.setPositiveButton("Có, đi đến play store",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						Intent intent = new Intent(Intent.ACTION_VIEW);
						intent.setData(Uri
								.parse("market://details?id=vn.ikame.android.truyenf17voz"));
						startActivity(intent);

						CHandler.store.setRate(true);
					}
				});

		alert.setNegativeButton("Không, tôi muốn thoát luôn",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						if(noti.getType() == 3 && !noti.isShow()){
							createNotificationAlert();
						} else {
							CategoryList.this.finish();
							System.gc();
							android.os.Process.killProcess(android.os.Process
									.myPid());
						}
					}
				});
		alert.setCancelable(true);
		alert.show();
	}
	public void createExit2Message() {
		alert = new AlertDialog.Builder(this);
//		alert.setTitle("Thoát ứng dụng");
		alert.setMessage("Bạn có thực sự muốn thoát ứng dụng?");
		alert.setPositiveButton("Có",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						if(noti.getType() == 3 && !noti.isShow()){
							createNotificationAlert();
						} else {
							CategoryList.this.finish();
							System.gc();
							android.os.Process.killProcess(android.os.Process
									.myPid());
						}
					}
				});

		alert.setNegativeButton("Không",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						
					}
				});
		alert.setCancelable(true);
		alert.show();
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_DOWNLOAD_PROGRESS:
			mProgressDialog = new ProgressDialog(this);
			mProgressDialog.setMessage("Loading...");
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(true);
			mProgressDialog.show();
			return mProgressDialog;
		default:
			return null;
		}
	}
	public void initCategory() {
		try {
			// Tạo task kết nối với server
			new AsyncTask<Void, Void, String>() {
				@Override
				protected void onPreExecute() {
					// Hiển thị thông báo
					showDialog(DIALOG_DOWNLOAD_PROGRESS);
				}

				@Override
				protected String doInBackground(Void... arg0) {
					try {

						Thread theard = new Thread() {
							@Override
							public void run() {
								try {

									int waited = 0;
									while (true && (waited < 10000)) {
										sleep(100);
										if (true) {
											waited += 100;
										}
									}

								} catch (Exception e) {
									// do nothing
								} finally {
									try {
										System.out.println("Không kết nối được đến server");
										dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
									} catch (Exception e) {
										// TODO: handle exception
									}
								}
							}
						};
						theard.start();

						CHandler.categoryList = XMLParser.getCategoryList(Constant.DATA_LINK + "services/appServer.php?index=content&appid=2&level=0");

					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						System.out.println("Không kết nối được đến server 2");
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						System.out.println("Không kết nối được đến server 3");
					}
					return "";
				}

				// Hoàn thành truy vấn
				@Override
				protected void onPostExecute(String result) {

					try {
						mGridViewAdapter = new ListCategoryAdapter(CategoryList.this, R.layout.maingridview, CHandler.categoryList);
						gridview.setAdapter(mGridViewAdapter);
						
						gridview.setOnItemClickListener(new OnItemClickListener() {

							@Override
							public void onItemClick(AdapterView<?> parent, View view,
									int position, long id) {
								// TODO Auto-generated method stub
								
								CHandler.cateID = CHandler.categoryList.get(position).getId();
								startActivity(new Intent(CategoryList.this, StoryList.class));
								CategoryList.this.finish();
							}

						});
						if (!CHandler.store.isShowAbout()) {
							createAboutMessage();
							CHandler.store.setShowAbout(true);

							StoryList.generalTracker.trackPageView("FromF17WithLove_installApp");
							StoryList.generalTracker.dispatch();

							StoryList.detailsTracker.trackPageView("FromF17WithLove_installApp");
							StoryList.detailsTracker.dispatch();
						}
						
					} catch (Exception e) {
					}
					try {
						dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
			}.execute();
		} catch (Exception e) {
		}
	}
	public void createAboutMessage() {
		alert = new AlertDialog.Builder(this);
		alert.setMessage(R.string.about);
		alert.setPositiveButton("Góp ý",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						final Intent emailIntent = new Intent(
								android.content.Intent.ACTION_SEND);

						/* Fill it with Data */
						emailIntent.setType("plain/text");
						emailIntent.putExtra(
								android.content.Intent.EXTRA_EMAIL,
								new String[] { "support@ikame.vn" });
						emailIntent.putExtra(
								android.content.Intent.EXTRA_SUBJECT,
								"Ứng dụng truyện ngắn - f145");
						emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
								"Nội dung: ");

						/* Send it off to the Activity-Chooser */
						startActivity(Intent.createChooser(emailIntent,
								"Send mail..."));
					}
				});

		alert.setNegativeButton("Đóng", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
			}
		});
		alert.setCancelable(false);
		alert.show();
	}
	
	public void initChapList() {
		try {
			// Tạo task kết nối với server
			new AsyncTask<Void, Void, String>() {
				@Override
				protected void onPreExecute() {
					// Hiển thị thông báo
					showDialog(DIALOG_DOWNLOAD_PROGRESS);
				}

				@Override
				protected String doInBackground(Void... arg0) {
					try {

						Thread theard = new Thread() {
							@Override
							public void run() {
								try {

									int waited = 0;
									while (true && (waited < 10000)) {
										sleep(100);
										if (true) {
											waited += 100;
										}
									}

								} catch (Exception e) {
									// do nothing
								} finally {
									try {
										System.out.println("Không kết nối được đến server");
										dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
									} catch (Exception e) {
										// TODO: handle exception
									}
								}
							}
						};
						theard.start();

						CHandler.storyName = CHandler.store.getStoryName();
						CHandler.chapID = CHandler.store.getChapID();
						CHandler.storyID = CHandler.store.getStoryID();
						CHandler.chapPos = CHandler.store.getChapPos();
						CHandler.cateID = CHandler.store.getCateID();
						CHandler.chapList = XMLParser.getChapList(Constant.DATA_LINK + "services/appServer.php?index=content&appid=2&level=2&cateid=" + CHandler.storyID + "&order=asc&remove=content");
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						System.out.println("Không kết nối được đến server 22");
						try {
							StoryList.detailsTracker.trackPageView("Connection error - ChapList");
							StoryList.detailsTracker.dispatch();
						} catch (Exception de) {
							// TODO: handle exception
						}

					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						System.out.println("Không kết nối được đến server 33");
						try {
							StoryList.detailsTracker
									.trackPageView("Connection error - ChapList");
							StoryList.detailsTracker.dispatch();
						} catch (Exception de) {
							// TODO: handle exception
						}
					}
					return "";
				}

				// Hoàn thành truy vấn
				@Override
				protected void onPostExecute(String result) {
					try {
						dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
					} catch (Exception e) {
						// TODO: handle exception
					}
					CHandler.chapID = CHandler.store.getChapID();
					CHandler.storyID = CHandler.store.getStoryID();
					CHandler.chapPos = CHandler.store.getChapPos();

					try{
						CHandler.chapName = CHandler.chapList.get(CHandler.chapPos)
								.getChapName();
//						CHandler.chapID = CHandler.chapList.get(CHandler.chapPos)
//								.getId();
						CategoryList.this.finish();
						startActivity(new Intent(CategoryList.this, Content.class));
					}catch (Exception e) {
						// TODO: handle exception
					}

				}
			}.execute();
		} catch (Exception e) {
		}
	}

	

}
